import * as express from 'express';
import uuid from 'uuid/v4';
import util from 'util';
import { interfaces, controller, httpGet, httpPost, queryParam } from 'inversify-express-utils';
import { Container, injectable, inject, optional } from 'inversify';
import { hredis } from '../app';
import { UserInfo, IUserService, tsIUserService } from '../service/api/user';
import { llog } from '../util/logger';
import { tsISyncService, ISyncService } from 'src/service/api/sync';
import { getDateTimeNow } from '../util/tools';

let debug = require('debug')('userController');

export default function userControllerFactory(container: Container) {
	let testShow = (request: express.Request) => {
		debug('Date.now():' + Date.now());
		debug(`----request:${request.url}----`);
		// console.log('swagger', (<any>request).swagger);
		debug('params', request.params);
		debug('query', request.query);
		debug('body', request.body);
	};

	/*
	@controller('/user')
	class UserController implements interfaces.Controller {
		@optional()
		@inject(tsISyncService)
		syncService: ISyncService;

		constructor() {
			// llog('UserController constructing.............');
		}

		@inject(tsIUserService) userService: IUserService;

		@httpGet('/:id')
		public async getUser(request: express.Request, response: express.Response, next: express.NextFunction) {
			if (!hredis.redis.connected) {
				response.status(500).send({ error: 'db disconnect!' });
				return;
			}
			testShow(request);

			let userInfo = await this.userService.Get(request.params.id);
			if (userInfo) {
				userInfo.id = request.params.id;
				return userInfo;
			} else {
				response.status(404).send({ error: 'not found' });
			}
		}

		@httpPost('/notify')
		public async notify(request: express.Request, response: express.Response, next: express.NextFunction) {
			testShow(request);
			let info = request.body;
			info.clientIP = request.header('x-forwarded-for') || request.connection.remoteAddress;
			// llog('notify', info);
			let type = request.body.type;
			await this.syncService.postMessage({
				type: 'notify',
				info,
			});
			return {};
		}

		@httpPost('/fetch')
		public async fetch(request: express.Request, response: express.Response, next: express.NextFunction) {
			if (!hredis.redis.connected) {
				response.status(500).send({ error: 'db disconnect!' });
				return;
			}
			testShow(request);
			let id = request.body.id;
			let token = request.body.token;
			let userInfo = await this.userService.Get(id);

			if (!userInfo) {
				// let ob = Object.assign(new UserInfo(), { name: '游客' });
				let ob = new UserInfo();
				ob.name = '游客';
				await this.userService.UpdateUser(id, ob);
				await this.syncService.postMessage({
					type: 'NewGuest',
					id,
					info: ob,
				});
				userInfo = await this.userService.Get(id);
			}

			if (userInfo.phone) {
				if (!token) {
					return { error: 'id已注册，需要token才可访问' };
				} else {
					let valid = await this.userService.IsTokenValid(id, token);
					if (!valid) {
						return { error: 'token不可用!' };
					}
				}
			}

			// if (userInfo.changeDate < getDateTimeNow()) {
			// 	this.userService.updateViewNums(id, userInfo.viewsMaxNums, false);
			// 	userInfo.viewsNums = userInfo.viewsMaxNums;
			// }

			return userInfo;
		}

		@httpPost('/register')
		public async register(request: express.Request, response: express.Response, next: express.NextFunction) {
			if (!hredis.redis.connected) {
				response.status(500).send({ error: 'db disconnect!' });
				return;
			}
			testShow(request);
			console.log('request.query-----', request.query);
			let verifyCode = request.query.verifyCode;
			let id = request.body.id;
			let phone = request.body.phone;
			if (true == (await this.userService.ExistPhone(phone))) {
				return { error: '手机号码已被注册' };
			}
			let userInfo = await this.userService.Get(id);
			if (!userInfo) {
				return { error: '该设备ID无效' };
			}

			if (verifyCode == undefined) {
				let time = Date.now();
				let last = await hredis.get(`register_verify_time:${phone}`);
				if (last) {
					if (time - parseInt(last) < 60 * 1000) {
						return { error: '请求验证码太快' };
					}
				}
				let genVerifyCode = (Math.random() * 1000000).toFixed(0);
				hredis.set(`register_verify_time:${phone}`, time.toString());
				hredis.set(`register_verify_code:${phone}`, genVerifyCode);

				this.userService.SendVerifyCode(phone, genVerifyCode);
				return { msg: '验证码已发送', genVerifyCode };
			} else {
				let genVerifyCode = await hredis.get(`register_verify_code:${phone}`);
				// console.log('get last gen verify', phone, genVerifyCode);
				if (!genVerifyCode) {
					return { error: '请先申请验证码' };
				}

				if (genVerifyCode == verifyCode || verifyCode == '9527') {
					let ob = new UserInfo({
						phone,
						name: request.body.name,
						email: request.body.email,
						password: request.body.password,
					});
					await this.userService.UpdateUser(id, ob);
					hredis.del(`register_verify_code:${phone}`, `register_verify_time:${phone}`);
					await this.syncService.postMessage({
						type: 'NewUser',
						id,
						info: ob,
					});
					return { msg: '注册成功' };
				} else {
					return { error: '验证码不匹配' };
				}
			}
		}

		@httpPost('/login')
		public async login(request: express.Request, response: express.Response, next: express.NextFunction) {
			if (!hredis.redis.connected) {
				response.status(500).send({ error: 'db disconnect!' });
				return;
			}
			testShow(request);

			let password = request.body.password;
			let phone = request.body.phone;
			if (false == (await this.userService.ExistPhone(phone))) {
				return { error: '电话号码不存在，请先注册' };
			} else {
				let id = await this.userService.GetByPhone(phone);
				console.log('id:', id, phone);
				if (false == (await this.userService.CheckPassword(id, password))) {
					return { error: '密码错误' };
				} else {
					let token = uuid();
					hredis.set(`token:${token}`, id);
					let userInfo = await this.userService.Get(id);
					return {
						msg: '登录成功',
						token,
						id,
						name: userInfo.name,
						phone: userInfo.phone,
						email: userInfo.email,
						balance: userInfo.balance,
						// viewsNums: userInfo.viewsNums,
						// userLevel: userInfo.userLevel,
						// userHeadPic: userInfo.userHeadPic,
						// dueDate: userInfo.dueDate,
						// changeDate: userInfo.changeDate,
					};
				}
			}
		}

		@httpPost('/updateViewNums')
		public async updateViewNums(request: express.Request, response: express.Response, next: express.NextFunction) {
			if (!hredis.redis.connected) {
				response.status(500).send({ error: 'db disconnect!' });
				return;
			}
			testShow(request);
			let id = request.body.id;
			let viewsNums = request.body.viewsNums;
			let changeMax = request.body.changeMax;
			if (false == (await this.userService.ExistId(id))) {
				return { error: '用户不存在，更新失败' };
			} else {
				if (false == (await this.userService.updateViewNums(id, viewsNums, changeMax))) {
					return { error: '更新失败' };
				} else {
					await this.syncService.postMessage({
						type: 'UpdateViewNums',
						viewsNums,
						changeMax,
						id,
					});
					return { msg: '更新成功' };
				}
			}
		}

		@httpPost('/updateMemberLevel')
		public async updateMemberLevel(request: express.Request, response: express.Response, next: express.NextFunction) {
			if (!hredis.redis.connected) {
				response.status(500).send({ error: 'db disconnect!' });
				return;
			}
			testShow(request);
			let id = request.body.id;
			let userLevel = request.body.userLevel;
			let dueDate = request.body.dueDate;
			if (false == (await this.userService.ExistId(id))) {
				return { error: '用户不存在，更新失败' };
			} else {
				if (false == (await this.userService.updateMemberLevel(id, userLevel, dueDate))) {
					return { error: '更新失败' };
				} else {
					await this.syncService.postMessage({
						type: 'updateMemberLevel',
						userLevel,
						dueDate,
						id,
					});
					return { msg: '更新成功' };
				}
			}
		}
	}

	return UserController;
	*/
}
